<?php

/**
 * user actions.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage user
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: actions.class.php 3501 2007-02-18 10:28:17Z fabien $
 */
class userActions extends sfActions
{
  public function executeIndex()
  {
    return $this->forward('user', 'list');
  }

  public function executeList()
  {
    $this->processSort();

    $this->processFilters();

    $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/user/filters');

    // pager
    $this->pager = new sfPropelPager('User', 20);
    $c = new Criteria();
    $this->addSortCriteria($c);
    $this->addFiltersCriteria($c);
    $this->pager->setCriteria($c);
    $this->pager->setPage($this->getRequestParameter('page', 1));
    $this->pager->init();
  }

  public function executeCreate()
  {
    return $this->forward('user', 'edit');
  }

  public function executeSave()
  {
    return $this->forward('user', 'edit');
  }

  public function executeEdit()
  {
    $this->user = $this->getUserOrCreate();

    if ($this->getRequest()->getMethod() == sfRequest::POST)
    {
      $this->updateUserFromRequest();

      $this->saveUser($this->user);

      $this->setFlash('notice', 'Your modifications have been saved');
      
      if (($this->user->getId() === $this->getUser()->getUserId()) and ($this->user->getUsername() !== $this->getUser()->getUsername()))
      {
      	$this->getUser()->signIn($user, false);
      }

      if ($this->getRequestParameter('save_and_add'))
      {
        return $this->redirect('@admin?module=user&action=create');
      }
      else if ($this->getRequestParameter('save_and_list'))
      {
        return $this->redirect('@admin?module=user&action=list');
      }
      else
      {
        return $this->redirect('@admin?module=user&action=edit&id='.$this->user->getId());
      }
    }
    else
    {
      $this->labels = $this->getLabels();
    }
  }

  public function executeDelete()
  {
    $this->user = UserPeer::retrieveByPk($this->getRequestParameter('id'));
    $this->forward404Unless($this->user);

    try
    {
      $this->deleteUser($this->user);
    }
    catch (PropelException $e)
    {
      $this->getRequest()->setError('delete', 'Could not delete the selected User. Make sure it does not have any associated items.');
      return $this->forward('user', 'list');
    }

    return $this->redirect('@admin?module=user&action=list');
  }

  public function handleErrorEdit()
  {
    $this->preExecute();
    $this->user = $this->getUserOrCreate();
    $this->updateUserFromRequest();

    $this->labels = $this->getLabels();

    return sfView::SUCCESS;
  }

  protected function saveUser($user)
  {
    $user->save();

  }

  protected function deleteUser($user)
  {
    $user->delete();
  }

  protected function updateUserFromRequest()
  {
    $user = $this->getRequestParameter('user');

      if ($user['email'] != $this->user->getEmail())
      {
        if (!$this->emailUnique($user['email'], $this->user->getId()))
        {
          $this->getRequest()->setError('email', __('Email is already in use'));
          return sfView::SUCCESS;
        }
        else
        {          	
          $this->user->setEmail($user['email']);
        }      	        
      }

      if ($user['username'] != $this->user->getUsername())
      {
        if (!$this->usernameUnique($user['username'], $this->user->getId()))
        {
          $this->getRequest()->setError('username', __('Username is already in use'));
          return sfView::SUCCESS;
        }
        else
        {          	
          $this->user->setUsername($user['username']);
        }      	        
      }
    if (isset($user['name']))
    {
      $this->user->setName($user['name']);
    }
    if (isset($user['password']))
    {
      $this->user->setHashedPassword($user['password']);
    }
    if (isset($user['credential']))
    {
      $this->user->setCredential($user['credential']);
    }
  }

  protected function getUserOrCreate($id = 'id')
  {
    if (!$this->getRequestParameter($id))
    {
      $user = new User();
    }
    else
    {
      $user = UserPeer::retrieveByPk($this->getRequestParameter($id));

      $this->forward404Unless($user);
    }

    return $user;
  }

  protected function processFilters()
  {
    if ($this->getRequest()->hasParameter('filter'))
    {
      $filters = $this->getRequestParameter('filters');

      $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/user/filters');
      $this->getUser()->getAttributeHolder()->add($filters, 'sf_admin/user/filters');
    }
  }

  protected function processSort()
  {
    if ($this->getRequestParameter('sort'))
    {
      $this->getUser()->setAttribute('sort', $this->getRequestParameter('sort'), 'sf_admin/user/sort');
      $this->getUser()->setAttribute('type', $this->getRequestParameter('type', 'asc'), 'sf_admin/user/sort');
    }

    if (!$this->getUser()->getAttribute('sort', null, 'sf_admin/user/sort'))
    {
    }
  }

  protected function addFiltersCriteria($c)
  {
    if (isset($this->filters['username_is_empty']))
    {
      $criterion = $c->getNewCriterion(UserPeer::USERNAME, '');
      $criterion->addOr($c->getNewCriterion(UserPeer::USERNAME, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['username']) && $this->filters['username'] !== '')
    {
      $c->add(UserPeer::USERNAME, strtr($this->filters['username'], '*', '%'), Criteria::LIKE);
    }
    if (isset($this->filters['name_is_empty']))
    {
      $criterion = $c->getNewCriterion(UserPeer::NAME, '');
      $criterion->addOr($c->getNewCriterion(UserPeer::NAME, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['name']) && $this->filters['name'] !== '')
    {
      $c->add(UserPeer::NAME, strtr($this->filters['name'], '*', '%'), Criteria::LIKE);
    }
    if (isset($this->filters['email_is_empty']))
    {
      $criterion = $c->getNewCriterion(UserPeer::EMAIL, '');
      $criterion->addOr($c->getNewCriterion(UserPeer::EMAIL, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['email']) && $this->filters['email'] !== '')
    {
      $c->add(UserPeer::EMAIL, strtr($this->filters['email'], '*', '%'), Criteria::LIKE);
    }
  }

  protected function addSortCriteria($c)
  {
    if ($sort_column = $this->getUser()->getAttribute('sort', null, 'sf_admin/user/sort'))
    {
      $sort_column = UserPeer::translateFieldName($sort_column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
      if ($this->getUser()->getAttribute('type', null, 'sf_admin/user/sort') == 'asc')
      {
        $c->addAscendingOrderByColumn($sort_column);
      }
      else
      {
        $c->addDescendingOrderByColumn($sort_column);
      }
    }
  }

  protected function getLabels()
  {
    return array(
      'user{username}' => 'Username:',
      'user{name}' => 'Name:',
      'user{email}' => 'Email:',
      'user{password}' => 'Password:',
      'user{credential}' => 'Credential:',
    );
  }
  
  private function emailUnique($email, $id)
  {
    $c = new Criteria();
    $c->add(UserPeer::EMAIL, $email);
    $c->add(UserPeer::ID, $id, Criteria::NOT_EQUAL);
          
    if (UserPeer::doSelectOne($c) instanceof User)
    {
      return false;
    } 
    
    return true;	
  }
  
  private function usernameUnique($username, $id)
  {
    $c = new Criteria();
    $c->add(UserPeer::USERNAME, $username);
    $c->add(UserPeer::ID, $id, Criteria::NOT_EQUAL);
          
    if (UserPeer::doSelectOne($c) instanceof User)
    {
      return false;
    } 
    
    return true;	  	
  }  
}
